package com.coolgor.coldot.schedule.Friday;

import com.coolgor.coldot.dto.stock.StockInfoExecution;
import com.coolgor.coldot.dto.wechat.qyh.QYHMessageExecution;
import com.coolgor.coldot.entity.stock.StockInfo;
import com.coolgor.coldot.enums.stock.StockInfoOperationStateEnum;
import com.coolgor.coldot.enums.wechat.qyh.QYHMessageOperationStateEnum;
import com.coolgor.coldot.service.stock.StockInfoService;
import com.coolgor.coldot.service.wechat.qyh.QYHMessageService;
import org.apache.ibatis.jdbc.Null;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class SinajsTask {

    @Value("${schedule.Friday.stock}")
    private boolean OnOff;

    @Autowired
    private QYHMessageService qyhMessageService;

    @Autowired
    private StockInfoService stockInfoService;

    @Autowired
    private StockService stockService;

    @Autowired
    private SinajsService sinajsService;

    // http://hq.sinajs.cn/list=sh601006,sh601727
    private  String BaseURL = "http://hq.sinajs.cn/list=";



//    @Scheduled(cron = "0/5 * * * * ? ") //测试用 每5秒执行一次
//    @Scheduled(cron = "0 0/1 * * * ? ") //测试用 每分钟执行一次
//    @Scheduled(cron = "0 0/1 9-11,13-15 * * ?") //正式用
    public void report()  {
        if (OnOff) {
            //在企业号中进行任务报告
            String operation = "";
            operation = "<))MACE任务报告((>\\n【广西今日配送情况】\\n仅统计纸质保单数据\\n" + operation ;
            //在盛古科技企业号的Friday中发送信息
            QYHMessageExecution qyhMessageExe1 = qyhMessageService.sendText(9L, "@all", null, null, operation, false);
        }
    }




    @Scheduled(cron = "0 30 9 * * ?") //上午执行1
    public void touchAM1() {
        if (OnOff) {
            if (stockService.isWorkday(new Date())) {
                sinajsService.holdMarketMinite(this.touchMinite());
                stockService.trackStock();
            }
        }
    }
    @Scheduled(cron = "0 31-59/1 9-10 * * ?") //上午执行2
    public void touchAM2() {
        if (OnOff) {
            if (stockService.isWorkday(new Date())) {
                sinajsService.holdMarketMinite(this.touchMinite());
                stockService.trackStock();
            }
        }
    }
    @Scheduled(cron = "0 0-30/1 10-11 * * ?") //上午执行3
    public void touchAM3() {
        if (OnOff) {
            if (stockService.isWorkday(new Date())) {
                sinajsService.holdMarketMinite(this.touchMinite());
                stockService.trackStock();
            }
        }
    }
    @Scheduled(cron = "0 0/1 13-14 * * ?") //下午执行1
    public void touchPM1() {
        if (OnOff) {
            if (stockService.isWorkday(new Date())) {
                sinajsService.holdMarketMinite(this.touchMinite());
                stockService.trackStock();
            }
        }
    }
    @Scheduled(cron = "0 0 15 * * ?") //下午执行2
    public void touchPM2() {
        if (OnOff) {
            if (stockService.isWorkday(new Date())) {
                sinajsService.holdMarketMinite(this.touchMinite());
                stockService.trackStock();
            }
        }
    }
    // 每天下午15:05执行一次，获取日数据
    @Scheduled(cron = "0 5 15 * * ?")
    public void touchDaily()  {
        if (OnOff) {
            if (stockService.isWorkday(new Date())) {
                sinajsService.holdMarketDaily(this.touchMinite());
            }
        }
    }


    private String touchMinite()  {
        List<String> stockCodeList;
        stockCodeList = stockService.getStockCodeList();
        if (null==stockCodeList || stockCodeList.size()<1) return null;

        System.out.println("SinajsTask => " + new Date());

        String urlStr = BaseURL;
        for (String code : stockCodeList) {
            urlStr += code + ",";
        }
        if (urlStr.endsWith(",")) {
            urlStr = urlStr.substring(0, urlStr.length()-1);
        }
        System.out.println(urlStr);

        try {
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            //默认就是Get，可以采用post，大小写都行，因为源码里都toUpperCase了。
            connection.setRequestMethod("GET");
            //是否允许缓存，默认true。1
            connection.setUseCaches(Boolean.FALSE);
            //是否开启输出输入，如果是post使用true。默认是false
            connection.setDoOutput(Boolean.TRUE);
            connection.setDoInput(Boolean.TRUE);
            //设置请求头信息
            connection.addRequestProperty("Connection", "close");
            //设置连接主机超时（单位：毫秒）
            connection.setConnectTimeout(8000);
            //设置从主机读取数据超时（单位：毫秒）
            connection.setReadTimeout(8000);
            //设置Cookie
            connection.addRequestProperty("Cookie","我们的Cookies" );
            //开始请求
//            Document doc = Jsoup.parse(connection.getInputStream(), "UTF-8", urlStr);
            // 这个网站必须设置成GB18030字符集，否则获取中文乱码
            Document doc = Jsoup.parse(connection.getInputStream(), "GB18030", urlStr);
            return doc.body().text();
//            sinajsService.holdMarketMinite(doc.body().text());
        } catch ( IOException ioe) {
            ioe.printStackTrace();
        }
        return null;
    }

}
